package com.example.demo.sort;

import java.util.stream.Stream;

/**
 * <pre>
 *  描述:
 * </pre>
 *
 * @author godelgnis(wujiaer)
 * @version 1.0.0
 * @date 2021/12/27 9:23
 */
public class Search {

    private static final int[] ARR = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};

    public static void main(String[] args) {

        System.out.println(orderSearch(ARR, 20));
        System.out.println(binarySearch(ARR, 20));
        System.out.println(binarySearchLoop(ARR, 20));


    }

    static int orderSearch(int[] arr, int value) {
        if (arr == null || arr.length == 0) {
            return -1;
        }
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == value) {
                return i;
            }
        }
        return -1;

    }

    static int binarySearch(int[] arr, int value) {
        int len;
        if (arr == null || (len = arr.length) == 0) {
            return -1;
        }
        int li = 0;
        int hi = len - 1;
        int mid = (li + hi) / 2;
        while (li <= hi) {
            if (arr[mid] == value) {
                return mid;
            } else if (value > arr[mid]) {
                li = mid + 1;
            } else {
                hi = mid - 1;
            }
            mid = (li + hi) / 2;
        }
        return -1;
    }

    static int binarySearchLoop(int[] arr, int value) {
        if (arr == null || arr.length == 0) {
            return -1;
        }
        return binarySearchLoop(arr, value, 0, arr.length - 1);
    }

    static int binarySearchLoop(int[] arr, int value, int li, int hi) {
        if (li <= hi) {
            int mid = (li + hi) / 2;
            if (arr[mid] == value) {
                return mid;
            } else if (value > arr[mid]) {
                return binarySearchLoop(arr, value, mid + 1, hi);
            } else {
                return binarySearchLoop(arr, value, li, mid - 1);
            }
        }
        return -1;
    }


}
